import axios from 'axios'
import nprogress from 'nprogress'
axios.defaults.baseURL = 'http://124.222.38.10:3004/users'
axios.interceptors.request.use((req) => {
  nprogress.start()
  req.headers['token'] = getToken()
  return req
})
axios.interceptors.response.use((res) => {
  nprogress.start()
  return res
})
function getToken() {
  let str = sessionStorage.getItem('user-login')
  if (!str) {
    return ''
  }
  return JSON.parse(str).token
}
let map = new Map([
  ['get', get],
  ['post', post],
  ['delete', del],
  ['put', put],
])
function get(options) {
  return axios.get(options.url, { params: options.data })
}
function post(options) {
  return axios.post(options.url, options.data)
}
function put(options) {
  return axios.put(options.url, options.data)
}
function del(options) {
  return axios.delete(options.url, options.data)
}
function request(options) {
  let mt = map.get(options.type)
  if (!mt) {
    return new Promise((resolve) => {
      resolve({
        code: 403,
        data: null,
        msg: '没有此种方法',
      })
    })
  }
  return mt(options)
}
export default request
